import subprocess
import re


def check_adb_environment():
    """检查ADB环境是否正常"""
    try:
        # 检查ADB是否安装
        version = subprocess.check_output(
            ["adb", "version"],
            stderr=subprocess.STDOUT
        ).decode("utf-8")
        print(f"ADB版本: {version.strip()}")

        # 检查设备连接
        devices = subprocess.check_output(
            ["adb", "devices"],
            stderr=subprocess.STDOUT
        ).decode("utf-8")

        # 解析设备列表
        device_list = []
        for line in devices.strip().split("\n")[1:]:
            if line.strip():
                device_id, status = line.strip().split("\t", 1)
                device_list.append((device_id, status))

        if not device_list:
            print("错误：未检测到连接的安卓设备。请确保设备已通过USB连接并开启USB调试模式。")
            return False
        elif any(status != "device" for _, status in device_list):
            print("错误：设备未授权或连接异常。请在设备上确认授权提示。")
            return False
        else:
            print(f"已连接设备: {len(device_list)}台")
            for device_id, status in device_list:
                print(f"  - {device_id} ({status})")
            return True

    except FileNotFoundError:
        print("错误：未找到ADB命令。请确保ADB已安装并添加到系统环境变量。")
        return False
    except subprocess.CalledProcessError as e:
        print(f"ADB命令执行失败: {e.output.decode('utf-8')}")
        return False


def get_installed_apps():
    """获取已安装应用列表"""
    if not check_adb_environment():
        return []

    try:
        # 使用ADB命令获取已安装应用的包名
        result = subprocess.check_output(
            ["adb", "shell", "pm", "list", "packages", "-f", "-3"],
            stderr=subprocess.STDOUT
        ).decode("utf-8", errors="ignore")

        apps = []
        for idx, line in enumerate(result.strip().split("\n")):
            # 假设已有package_name变量
            print(f"解析第 {idx + 1} 行: {line}")

            # 尝试使用正则表达式解析
            match = re.search(r"package:([^=]+)=([^=]+)", line)
            if not match:
                # 尝试更宽松的正则表达式
                match = re.search(r"package:(.+?)=(.+)", line)
                if not match:
                    # 使用字符串分割作为最后手段
                    if "package:" in line:
                        parts = line.strip().split("=", 1)
                        if len(parts) == 2:
                            apk_part = parts[0]
                            package_name = parts[1]

                            # 提取APK路径和包名
                            apk_path = apk_part.replace("package:", "").strip()

                            # 处理可能的引号
                            if package_name.startswith(('"', "'")) and package_name.endswith(('"', "'")):
                                package_name = package_name[1:-1]
                        else:
                            print(f"警告：第 {idx + 1} 行格式异常，无法分割: {line}")
                            continue
                    else:
                        print(f"警告：第 {idx + 1} 行不包含'package:'前缀: {line}")
                        continue
                else:
                    apk_path, package_name = match.groups()
            else:
                apk_path, package_name = match.groups()

            # 获取应用名称
            try:
                app_info = subprocess.check_output(
                    ["adb", "shell", "dumpsys", "package", package_name],
                    stderr=subprocess.STDOUT
                ).decode("utf-8", errors="ignore")

                app_name = "未知应用"

                # 尝试多种方式提取应用名称
                label_match = re.search(r'applicationLabel=([^"\n]+)', app_info)
                if label_match:
                    app_name = label_match.group(1).strip()
                else:
                    label_match = re.search(r'nonLocalizedLabel=([^"\n]+)', app_info)
                    if label_match:
                        app_name = label_match.group(1).strip()
                    else:
                        res_match = re.search(r'labelRes=0x([0-9a-f]+)', app_info)
                        if res_match:
                            res_id = res_match.group(1)
                            app_name = f"资源ID:{res_id}"
            except Exception as e:
                print(f"获取 {package_name} 应用名称失败: {e}")
                app_name = "未知应用"

            # 获取版本信息
            try:
                version_name = "N/A"
                version_code = "N/A"

                version_match = re.search(r'versionName=([^\s\n]+)', app_info)
                if version_match:
                    version_name = version_match.group(1).strip()

                code_match = re.search(r'versionCode=(\d+)', app_info)
                if code_match:
                    version_code = code_match.group(1).strip()
            except Exception as e:
                print(f"获取 {package_name} 版本信息失败: {e}")

            apps.append({
                "package_name": package_name,
                "app_name": app_name,
                "version_code": version_code,
                "version_name": version_name,
            })

        return apps

    except subprocess.CalledProcessError as e:
        print(f"获取应用列表失败: {e.output.decode('utf-8')}")
        return []


# 打开应用
def open_app(package_name):
    try:
        subprocess.check_output(
            ["adb", "shell", "am", "start", "-n", f"{package_name}/.MainActivity"],
            stderr=subprocess.STDOUT
        )
        print(f"已尝试打开应用: {package_name}")
    except subprocess.CalledProcessError as e:
        print(f"打开应用失败: {e.output.decode('utf-8')}")


# 卸载应用
def uninstall_app(package_name):
    try:
        result = subprocess.check_output(
            ["adb", "shell", "pm", "uninstall", package_name],
            stderr=subprocess.STDOUT
        ).decode("utf-8")
        print(f"卸载结果: {result.strip()}")
    except subprocess.CalledProcessError as e:
        print(f"卸载应用失败: {e.output.decode('utf-8')}")


# 示例使用
if __name__ == "__main__":
    # 检查ADB环境
    if check_adb_environment():
        # 获取应用列表
        apps = get_installed_apps()
        print(f"已安装应用数量: {len(apps)}")

        # 打印前10个应用信息
        for app in apps[:10]:
            print(f"应用名: {app}")
            # print(f"应用名: {app['app_name']}")
            # print(f"包名: {app['package_name']}")
            # print(f"版本号: {app['version_code']}")
            # print(f"版本名: {app['version_name']}")
            print("-" * 30)